<template>
  <div style="height: 100%;background-color:white ;">
    <el-row>
      <el-col :span="14">
        <el-button size="small" type="success" @click="releaseAllBook">发布图书</el-button>
        <el-button plain size="small" type="success" @click="importBook('')">导入文件</el-button>
        <el-upload action="/pmph/action/book/fillUp" style="display: inline-block"
                   accept=".xlsx" :show-file-list="false"
                   :on-success="fillUpOnSuccess">
          <el-button size="small">批量补录</el-button>
        </el-upload>

        <el-button size="small" @click="downLoad()">下载补录模板</el-button>
      </el-col>
      <el-col :span="8" style="right: auto">
      </el-col>
      <DraftSearch ref="draftSearch" :bookSubTagList="bookSubTagList" @advanceConfirm="advanceConfirm"></DraftSearch>
    </el-row>
    <el-row>
      <el-table highlight-current-row :data="draftTableData" border style="width: 100%;" stripe :height="tableHeight"
                @selection-change="handleSelectionChange">
        <el-table-column
          v-model="multipleSelection"
          type="selection"
          :selectable="(row) => !(row.bookType !== 0 && row.qualityStatus === 1)"
          width="55">
        </el-table-column>
        <el-table-column label="图书名称" min-width="240" prop="name">
          <template slot-scope="scope">
            <span v-html="scope.row.name"></span>
          </template>
        </el-table-column>
        <el-table-column label="图书类型" min-width="140" prop="name">
          <template slot-scope="scope">
            <span v-html="CONST.BOOK_TYPE.find(item => item.value === scope.row.bookType).label"></span>
            <!-- 增值  增值+电子书  显示  当付型时,才能发布 -->
            <span v-if="scope.row.bookType !== 0" style="color: red;"
                  v-html="CONST.BOOK_QUALITY_STATUS[scope.row.qualityStatus]"></span>
          </template>
        </el-table-column>
        <el-table-column label="图书分类" min-width="150" prop="categoryStr"></el-table-column>
        <el-table-column label="书号" min-width="180" prop="isbn"></el-table-column>
        <el-table-column label="版本号" min-width="80" prop="version"></el-table-column>
        <el-table-column :show-overflow-tooltip="false" label="导入状态" min-width="120" prop="status">
          <template slot-scope="scope">
            <span v-if="scope.row.status === 0">导入成功</span>
            <span v-if="scope.row.status === 2" style="color: #EC0000">导入失败
              <el-popover
                :content="failureReason"
                trigger="hover"
                v-on:show="openShow(scope.$index)">
                 <el-button slot="reference" style="margin-left: 10px" type="text"><a style="color: #EC0000">详情</a><i
                   class="el-icon-warning-outline el-icon--right" style="color: #EC0000"></i></el-button>
            </el-popover></span>
            <span v-if="scope.row.status === 3">导入中</span>
          </template>
        </el-table-column>
        <el-table-column label="导入时间" min-width="150" prop="createdTime"></el-table-column>
        <el-table-column :show-overflow-tooltip="false" fixed="right" label="操作" min-width="200">
          <template slot-scope="scope">
            <span v-if="scope.row.status === 2">
              <el-link type="primary" @click="forceImportBook(scope.row.id)">强制导入</el-link>
            </span>
            <span v-if="scope.row.bookType === 2 || (scope.row.status === 2)">
              <el-link type="primary" @click="importBook(scope.row.id)">导入XML文件</el-link>
            </span>
            <span v-if="scope.row.bookType !== 2 && scope.row.status === 0"><el-link
              type="primary" @click.prevent="detail(scope.row.id)">详情</el-link></span>
            <span v-if="scope.row.status === 0 &&
            ((scope.row.bookType !== 0 && scope.row.qualityStatus === 2) || scope.row.bookType === 0)"><el-link
              type="primary"
              @click.prevent="release(scope.row.id)">发布</el-link></span>
            <span v-if="scope.row.bookType !== 0"><el-link type="primary"
                                                           @click.prevent="editIncreaseMetadata(scope.row.id,scope.$index)">增值元数据</el-link></span>
            <span v-if="scope.row.bookType !== 2 && scope.row.status === 0"><el-link type="primary"
                                                                                     @click.prevent="editMetadata(scope.row.id,scope.$index)">元数据</el-link></span>
            <span v-if="scope.row.status === 0"><el-link type="primary"
                                                         @click.prevent="logShow(scope.row.id,scope.row.name)">日志</el-link></span>
            <span><el-link type="danger" @click.prevent="del(scope.row.id)">删除</el-link></span>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <div>
        <el-pagination
          :total="totalNum"
          :page-size.sync="queryParam.pageSize"
          :current-page.sync="queryParam.currentPage"
          :page-sizes="[5, 10, 15, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          style="text-align: right;"></el-pagination>
      </div>
    </el-row>
    <el-dialog :visible.sync="uploadVisible" title="上传文件" width="400px">
      <el-upload :action="'/pmph/action/book/importBook?id=' + importBookId + '&forceFlag=' + forceFlag"
                 :on-success="onSuccess"
                 :show-file-list="true" accept=".zip" class="upload-demo"
                 drag
                 style='text-align:center;'>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">仅支持扩展名为.zip的文件</div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import DraftSearch from "../book/DraftSearch";
export default {
  name: "DraftTable",
  components: {
    DraftSearch,
  },
  data() {
    return {
      tableHeight: 0,
      draftTableData: [],
      uploadVisible: false,
      tableData: [],
      totalNum: 0,
      multipleSelection: [],
      bookSubTagList: [],
      queryParam: {
        currentPage: 1,
        pageSize: 10,
      },
      failureReason: '',
      forceFlag: '',
      importBookId: ''
    }
  },
  methods: {
    fillUpOnSuccess() {
      this.getTableData()
    },
    //复选框选中事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    importFile: function () {
      this.$router.push("/importTable")
    },
    releaseAllBook: function () {
      if (this.multipleSelection.length <= 0) {
        this.$message.warning("请选择知识");
        return;
      }
      this.$confirm('确定发布？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = new URLSearchParams();
        param.append("selectAll", JSON.stringify(this.multipleSelection))
        this.axios.post('/pmph/action/book/releaseAllBook',param)
          .then((response) => {
            this.getTableData()
            this.$emit("released")
          });
      })
    },
    advanceConfirm(queryParam) {
      this.queryParam = queryParam
      this.getTableData()
    },
    detail: function (id) {
      this.$router.push({
          path: '/bookDetail',
          query: {id: id, showEdit: "draft"}
        }
      )
    },
    logShow: function (id, name) {
      this.$router.push({
          path: '/bookLog',
          query: {id: id, name: name}
        }
      )
    },
    showMetadata: function (id) {
      this.$router.push({
          path: '/showMetadata',
          query: {id: id}
        }
      )
    },
    editMetadata: function (id, index) {
      this.$router.push({
          name: 'editMetadata',
          params: {id: id, metadata: this.draftTableData[index].metadata}
        }
      )
    },
    editIncreaseMetadata(id, index) {
      this.$router.push({
          name: 'editIncreaseMetadata',
          params: {
            id: id,
            formData: this.draftTableData[index].metadata.increase,
            pageType: 'book',
            bookType: this.draftTableData[index].bookType
          }
        }
      )
    },
    downLoad: function () {
      window.location.href = '/pmph/action/book/downLoad'
    },
    del: function (id) {
      this.$confirm('是否删除？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.get('/pmph/action/book/deleteBookById', {
          params: {
            id: id,
          }
        }).then((response) => {
          this.getTableData()
        })
      })
    },
    release: function (id) {
      this.$confirm('确定发布？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.get('/pmph/action/book/release', {
          params: {
            id: id,
          }
        }).then((response) => {
          this.getTableData();
          this.$emit("released")
        });
      })
    },
    getTableData: function () {
      this.axios.get('/pmph/action/book/selectDraftList', {
        params: this.queryParam
      }).then((response) => {
        this.draftTableData = response.data.records;
        this.totalNum = response.data.total;
        if (this.draftTableData.find(item => item.status === 3)) {
          this.timeout = setTimeout(this.getTableData, 3000);
        }
      })
    },
    openShow: function (index) {
      this.failureReason = this.draftTableData[index].failureReason
    },
    onSuccess: function () {
      this.uploadVisible = false;
      this.$message.success("导入任务提交成功, 请耐心等待");
      this.getTableData()
    },
    forceImportBook(id) {
      this.forceFlag = true;
      this.importBookId = id;
      this.uploadVisible = true;
    },
    importBook(id) {
      this.forceFlag = false;
      this.importBookId = id;
      this.uploadVisible = true;
    }
  },
  watch: {
    queryParam: {
      handler() {
        this.getTableData()
      },
      deep: true,
    },
    draftTableData(val) {
      for (let draftBook of val) {
        draftBook.categoryStr = []
        if (Array.isArray(draftBook.category)) {
          let cntTagList = this.bookSubTagList
          for (let item of draftBook.category) {
            let cntTag = cntTagList.find(tag => tag.id === item)
            draftBook.categoryStr.push(cntTag.name)
            cntTagList = cntTag.children
          }
        }
        draftBook.categoryStr = draftBook.categoryStr.join(" / ")
      }
    }
  },
  activated() {
    this.tableHeight = CONST.WORKSPACE_HEIGHT - 140;
    this.axios.get('/pmph/action/tag/selectBookSubTagTree').then((response) => {
      this.bookSubTagList = response.data
      this.getTableData()
    })
  }
}
</script>

<style scoped>

</style>
